package com.itheima.project.knowledge;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;

import com.itheima.project.*;

import com.itheima.project.constant.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SubPageContentFragment extends Fragment {

    public static final String CHILDREN_BEAN = "children_bean";

    private KnowledgeTreeEntity.DataBean.ChildrenBean mChildrenBean;

    private int mCurrentPage = 0;

    private Context context;
    private List<KnowledgeSubPageEntity.DataBean.DatasBean> mList = new ArrayList<>();
    //下拉刷新控件
    private SwipeRefreshLayout srlFragment;
    //正文Fragment
    private RecyclerView rvFragment;
    //正文 Fragment Adapter
    private SubPageContentAdapter subPageContentAdapter;

    public static SubPageContentFragment newInstance(KnowledgeTreeEntity.DataBean.ChildrenBean childrenBean) {
        SubPageContentFragment fragment = new SubPageContentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(CHILDREN_BEAN, childrenBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.knowledge_subpage_content_fragment, container, false);
        srlFragment = inflate.findViewById(R.id.srl_knowledge_subpage_content_fragment);
        rvFragment = inflate.findViewById(R.id.rv_knowledge_subpage_content_fragment);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
        initEvent();
    }

    private void initData() {
        context = getContext();
        Bundle bundle = getArguments();
        if (bundle != null) {
            mChildrenBean = (KnowledgeTreeEntity.DataBean.ChildrenBean) bundle.getSerializable(CHILDREN_BEAN);
        }else {
            throw new RuntimeException("Please check indicator list!");
        }
        subPageContentAdapter = new SubPageContentAdapter(mList, context);
        rvFragment.setLayoutManager(new LinearLayoutManager(context));
        rvFragment.setAdapter(subPageContentAdapter);

        requestSubPageList();

    }

    private void requestSubPageList() {
        String url = String.format(Locale.CHINA,ApiInterface.KNOWLEDGE_FEED_URL + "?cid=%d", 0, mChildrenBean.getId());
        OkHttpUtil.enqueue(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final KnowledgeSubPageEntity knowledgeSubPageEntity = new Gson().fromJson(string, KnowledgeSubPageEntity.class);
                if (knowledgeSubPageEntity.getErrorCode() ==0) {
                    HandlerUtil.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mCurrentPage == 0) {
                                mList.clear();
                            }
                            mList.addAll(knowledgeSubPageEntity.getData().getDatas());
                            subPageContentAdapter.notifyDataSetChanged();
                            srlFragment.setRefreshing(false);
                        }

                    });
                }

            }
        });
    }

    private void initEvent() {
        srlFragment.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 0;
                requestSubPageList();
            }
        });
        rvFragment.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) rvFragment.getLayoutManager();
                int itemCount = layoutManager.getItemCount();
                if (itemCount == 0) {
                    return;
                }
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition == itemCount-1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mCurrentPage += 1;
                    srlFragment.setRefreshing(true);
                    requestSubPageList();
                }
            }
        });
    }
    public  void scrollToTop(){
        rvFragment.scrollToPosition(0);
    }

}
